package bank.passbook.service;

import java.sql.SQLException;
import java.util.ArrayList;

import bank.exception.DepositException;
import bank.exception.NotFoundAccountException;
import bank.exception.WithdrawalException;
import bank.passbook.dao.PassbookDAO;
import bank.passbook.vo.Passbook;

public class PassbookService {
	private PassbookDAO dao = PassbookDAO.getInstance();
	private static PassbookService service = new PassbookService();
	private PassbookService() {}
	public static PassbookService getInstance() {
		return service;
	}
	public void depositMoney(String accountNumber, int money) throws Exception {
		int count = dao.updatePassbookById(accountNumber, money);
		if(count == 1){
			System.out.println(accountNumber + "계좌에 정상 입금되었습니다.");
		} else {
			throw new DepositException(accountNumber + "계좌에서 입금을 실패하였습니다.");
		}
	}
	
	public void withdrawal(String accountNumber, int money) throws Exception {
		Passbook passbook = dao.selectPassbookByAccountNo(accountNumber);
		
		if(passbook == null){
			throw new NotFoundAccountException(accountNumber + "계좌가 존재하지 않습니다.");
		}
		
		if(passbook.getMoney() < money){
			throw new WithdrawalException(accountNumber + "계좌에 잔액이 부족합니다.\n" + "잔액 : " + passbook.getMoney() + ", 출금액 : " + money);
		}
		
		int count = dao.updatePassbookById(accountNumber, (-money));
		
		if(count == 1){
			System.out.println(accountNumber + "계좌에 정상 출금되었습니다.");
		} else {
			throw new WithdrawalException(accountNumber + "계좌에서 출금을 실패하였습니다.");
		}
	}
	
	public Passbook findPassbookByAccountNo(String accountNumber) throws Exception{
		return dao.selectPassbookByAccountNo(accountNumber);
	}
	
	public ArrayList<Passbook> findPassbookList() throws Exception{
		return dao.selectPassbookList();
	}
	
	public void interestAccrues() throws SQLException {
		dao.updatePassbookByInterest();
	}
}
